package com.xian.minetomcat.simpledemo.day1;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

/**
 * http请求服务器
 * 1.监听TCP端口，等待浏览器连接；
 * 2.接受TCP连接后，创建一个线程处理该TCP连接：
 *  2.1 接收浏览器发送的HTTP请求；
 *  2.2 解析HTTP请求；
 *  2.3 处理请求；
 *  2.4 发送HTTP响应；
 *  2.5 重复1～4直到TCP连接关闭。
 *
 * @author zhan
 * @version 2024/2/3
 */
public class SimpleHttpHandler implements HttpHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public void handle(HttpExchange exchange) throws IOException {
        // HttpExchange封装了原始HTTP协议的解析
        String method = exchange.getRequestMethod();
        URI uri = exchange.getRequestURI();
        String path = uri.getPath();
        String query = uri.getRawQuery();
        logger.info("{}: {}?{}", method, path, query);
        // 输出响应的Header
        Headers responseHeaders = exchange.getResponseHeaders();
        responseHeaders.set("Content-Type", "text/html; charset=utf-8");
        responseHeaders.set("Cache-Control", "no-cache");
        // 设置HTTP响应码
        exchange.sendResponseHeaders(200, 0);
        // 输出的响应内容
        String res = "<h1>Hello, world.</h1><p>" + LocalDateTime.now().withNano(0) + "</p>";;
        try (OutputStream out = exchange.getResponseBody()) {
            out.write(res.getBytes(StandardCharsets.UTF_8));
        }
    }
}
